package org.tinygame.herostory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.tinygame.herostory.codec.GameMsgCoder;
import org.tinygame.herostory.codec.GameMsgDecoder;
import org.tinygame.herostory.codec.GameMsgEncoder;
import org.tinygame.herostory.handler.CmdHandlerFactory;

public class ServerMain {

    public static void main(String[] args) {
        CmdHandlerFactory.init();//初始化对象生成
        GameMsgCoder.init();//初始化对象生成

        //处理客户端连接的boss线程池，建好channel交给worker处理，boss只负责建立连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //真实工作的线程池
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(bossGroup,workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        //childHandler处理客户端的请求流程
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(
                    //编解码
                    new HttpServerCodec(),
                    //限制消息长度
                    new HttpObjectAggregator(65535),
                    //处理websocket协议
                    new WebSocketServerProtocolHandler("/websocket"),
                    //自定义解码器
                    new GameMsgDecoder(),
                    //自定义编码器
                    new GameMsgEncoder(),
                    //自定义消息处理handler
                    new GameMsgHandler()
                );
            }
        });

        try {
            ChannelFuture future = bootstrap.bind(12345).sync();

            if(future.isSuccess()){
                System.out.println("服务启动成功");
            }

        future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
